package com.strive.village.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.strive.village.common.Const;
import com.strive.village.common.Result;
import com.strive.village.entity.dto.PasswordDto;
import com.strive.village.entity.SysRole;
import com.strive.village.entity.SysUser;
import com.strive.village.entity.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author strivePeng
 * @since 2024-04-18
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder; // 密码加密方式

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result getUserList(String username) {
        // 分页查询
        Page<SysUser> userPage = sysUserService.page(getPage(), new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), "username", username));
        userPage.getRecords().forEach(user -> {
            user.setRoles(sysRoleService.listRolesByUserId(user.getId()));
        });
        return Result.success(userPage);
    }

    /**
     * 回显用户信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result getUserInfo(@PathVariable("id") Long userId) {
        SysUser user = sysUserService.getById(userId);
        Assert.notNull(user, "找不到改用户");
        // 查找相关的角色信息
        List<SysRole> roleList = sysRoleService.listRolesByUserId(userId);
        user.setRoles(roleList);
        return Result.success(user);
    }

    /**
     * 新增用户
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result addUser(@RequestBody SysUser user) {
        user.setCreated(LocalDateTime.now());
        // user.setStatu(Const.STATUTS_ON);
        user.setPassword(bCryptPasswordEncoder.encode(Const.DEFAULT_PASSWORD));
        user.setAvatar(Const.DEFAULT_AVATAR);

        sysUserService.save(user);
        return Result.success("用户添加成功");
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result updateUser(@RequestBody SysUser user) {
        user.setUpdated(LocalDateTime.now());
        sysUserService.updateById(user);
        return Result.success("更新用户信息成功");
    }

    /**
     * 删除用户信息
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result deleteUser(@RequestBody Long[] ids) {
        sysUserService.removeByIds(Arrays.asList(ids));
        // 删除关联表信息
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));
        return Result.success("删除用户信息成功");
    }

    /**
     * 分配用户角色
     */
    @PostMapping("/assignRole/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result assignRole(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {
        List<SysUserRole> userRoleList = new ArrayList<>();
        Arrays.stream(roleIds).forEach(roleId -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            userRoleList.add(userRole);
        });

        // 删除源库中的用户相关内容
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(userRoleList);

        // 清除redis的权限缓存
        sysUserService.clearUserAuthorityInfo(sysUserService.getById(userId).getUsername());

        return Result.success("用户角色信息更新成功");
    }

    /**
     * 重置用户密码
     */
    @PostMapping("/resetPassword")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result resetPassword(@RequestBody Long userId) {
        SysUser user = sysUserService.getById(userId);
        // 重置为默认密码
        user.setPassword(bCryptPasswordEncoder.encode(Const.DEFAULT_PASSWORD));
        user.setUpdated(LocalDateTime.now());

        sysUserService.updateById(user);
        return Result.success("密码重置成功");
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody PasswordDto passDto, Principal principal) {
        SysUser user = sysUserService.getByUsername(principal.getName());
        boolean matches = bCryptPasswordEncoder.matches(passDto.getCurrentPassword(), user.getPassword());
        if (!matches) {
            return Result.fail("旧密码不正确");
        }

        user.setPassword(bCryptPasswordEncoder.encode(passDto.getPassword()));
        user.setUpdated(LocalDateTime.now());
        sysUserService.updateById(user);
        return Result.success("修改密码成功");
    }
}
